﻿using System;
using System.IO;
using SdmxMl.SmsImportCfg;

namespace GeoPlugIn
{
    /// <summary>
    /// Class for reading State & Territories Excel source document
    /// </summary>
    public class ExcelSTreader : IReader
    {
        #region Internal Members

        private ExcelDataReader.ExcelDataReader spreadsheet = null;

        #endregion

        #region Properties

        public string Diagnostic { get; set; }
        public string VersionDate { get; set; }
        public string VersionSdmx { get; set; }


        public ExcelDataReader.ExcelDataReader Spreadsheet
        {
            get { return spreadsheet; }
        }

        public string NameStateTerritory
        {
            get { return "StaGeb_Liste"; }
        }
        #endregion

        #region Constructor

        public ExcelSTreader(string path)
        {
            FileStream fs = null;
            Diagnostic = string.Empty;
            try
            {
                fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);

                spreadsheet = new ExcelDataReader.ExcelDataReader(fs);
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }
        #endregion

        #region Pre-validation control

        /// <summary> Basic checking of source Excel document</summary>
        /// <returns>True on error</returns>
        /// <remarks>Set error explanation in Diagnostic property</remarks>
        public bool ValidatePreConditions()
        {
            // At least sheets must be loaded
            bool onError = spreadsheet == null;

            Diagnostic = string.Empty;

            if (!onError)
            {
                // two sheets at least
                if (spreadsheet.WorkbookData == null ||
                    spreadsheet.WorkbookData.Tables == null ||
                    spreadsheet.WorkbookData.Tables.Count != 2)
                {
                    onError = true;
                    Diagnostic = "Invalid count of workbook in Excel document !";
                }
                
                // Sheet Naming
                if (!onError &&
                    (spreadsheet.WorkbookData.Tables[0].TableName != "ReadMe" ||
                    spreadsheet.WorkbookData.Tables[1].TableName != NameStateTerritory ))
                {
                    onError = true;
                    Diagnostic = "Unexpected naming of Workbooks!" + Environment.NewLine +
                        "Expected: 'ReadMe', found: " + spreadsheet.WorkbookData.Tables[0].TableName +
                        Environment.NewLine +
                         "Expected: 'StaGeb_Liste', found: " + spreadsheet.WorkbookData.Tables[1].TableName;
                       
                }
                
                // Sheets columns fixed at 7 and 24
                if (!onError && 
                    (spreadsheet.WorkbookData.Tables[0].Columns.Count != 7 ||
                    spreadsheet.WorkbookData.Tables[1].Columns.Count != 24))
                {
                    onError = true;
                    Diagnostic = "Unexpected column count in Workbooks!" + Environment.NewLine +
                        "'ReadMe' expected 7, found: " + spreadsheet.WorkbookData.Tables[0].Columns.Count +
                        Environment.NewLine +
                         "'StaGeb_Liste' expected 24, found: " + spreadsheet.WorkbookData.Tables[1].Columns.Count;
                }

                // Obtains Date and sdmx version
                VersionDate = string.Empty;
                VersionSdmx = string.Empty;

                WorkSheetHelper wsh = new WorkSheetHelper(spreadsheet.WorkbookData.Tables[0]);
                for (int row = 1; row <= spreadsheet.WorkbookData.Tables[0].Rows.Count; row++)
                {
                    string versionText = wsh.GetCellContent(row, 1);
                    versionText.Trim();

                    // Is this the metadata validity date
                    if (versionText.StartsWith("Version:") && VersionDate.Length == 0)
                    {
                        try
                        {
                            // Year required
                            int year = Convert.ToInt32(versionText.Substring(versionText.Length - 4));

                            // Do we have a full date
                            DateTime dtResult = DateTime.MinValue;
                            if (DateTime.TryParse(versionText.Substring(8), out dtResult))
                            {
                                VersionDate = dtResult.ToString("yyyy-MM-dd");
                            }
                            else
                            {
                                VersionDate = year.ToString() + "-01-01";
                            }
                        }
                        catch 
                        {
                            throw new ApplicationException("Unable to fetch Version year!");
                        }
                    }

                    // SDMX version for new version of artefact
                    if (versionText.StartsWith("Version SDMX:") && VersionSdmx.Length == 0)
                    {
                        VersionSdmx = versionText.Substring(13).Trim(' ');
                    }
                }
            }

            return onError;
        }

        #endregion
    }
}
